<template>
  <el-select
    ref="departmentRemoteSelect"
    v-model="selectVal"
    filterable
    remote
    :remote-method="queryDataAction"
    :disabled="disabled"
    :loading="loading"
    :placeholder="placeholder"
    :clearable="clearable"
    @change="handleChange"
  >
    <el-option
      v-for="(item,key) in list"
      :key="key"
      :label="`${item.departmentName}(${item.departmentCode})`"
      :value="item.departmentId"
    >
    </el-option>
  </el-select>
</template>
<script>
import { getDepartmentList } from '@/api/supplier/components';
export default {
  name: 'DepartmentRemoteSelect',
  props: {
    value: [String, Number, Array],
    placeholder: { type: String, default: '请输入部门名称' },
    clearable: { type: Boolean, default: true },
    disabled: { type: Boolean, default: false },
  },
  data () {
    return {
      loading: false,
      selectVal: this.value || '',
      list: [],
    };
  },
  watch: {
    value: {
      handler (val) {
        if (val) {
          this.selectVal = val;
        }
      },
      immediate: true,
    },
  },
  methods: {
    handleChange (val) {
      // 值回显父组件
      this.$emit('input', val);
      // change事件
      this.$emit('change', val);
      //
      this.$emit('onSelected', this.list.find(item => item.departmentId === val))
    },
    async queryDataAction (param) {
      console.log('queryDataAction :>> ', param);
      this.loading = true;
      const resp = await getDepartmentList({ departmentNameLike: param });
      this.loading = false;
      if (resp && resp.result && resp.result.data && resp.result.data.length) {
        this.list = resp.result.data
      } else {
        this.list = []
      }
    },
    resetSelectVal () {
      this.selectVal = undefined
    }
  }
};
</script>
